package com.hehui.module.ossSTS.service.Impl;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.hehui.module.ossSTS.service.IOssService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Random;

@Service
public class OssServiceImpl implements IOssService {
    //地域
    private String regionId = "oss-cn-chengdu";
    //公网：sts.cn-chengdu.aliyuncs.com
    //VPC：sts-vpc.cn-chengdu.aliyuncs.com
    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.AccessKeyId}")
    private String AccessKeyId;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.roleArn}")
    private String roleArn;
    //用来标识临时访问凭证的名称，建议使用不同的应用程序用户来区分。
    private String roleSessionName = "RoleName";
    String policy = "{\n" +
            "    \"Version\": \"1\", \n" +
            "    \"Statement\": [\n" +
            "        {\n" +
            "            \"Action\": [\n" +
            "                \"oss:*\"\n" +
            "            ], \n" +
            "            \"Resource\": [\n" +
            "                \"acs:oss:*:*:*\" \n" +
            "            ], \n" +
            "            \"Effect\": \"Allow\"\n" +
            "        }\n" +
            "    ]\n" +
            "}";


    @Override
    public HashMap<String, Object> getSTS(Long DurationSeconds) {
        HashMap<String, Object> map = new HashMap<>();
        try {
            // 添加endpoint（直接使用STS endpoint，前两个参数留空，无需添加region ID）
            DefaultProfile.addEndpoint("", "", "Sts", endpoint);
            // 构造default profile（参数留空，无需添加region ID）
            IClientProfile profile = DefaultProfile.getProfile("", AccessKeyId, accessKeySecret);
            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(roleArn);
            request.setRoleSessionName(roleSessionName + new Random().nextInt(100));
            request.setPolicy(policy); // 若policy为空，则用户将获得该角色下所有权限
            request.setDurationSeconds(DurationSeconds); // 设置凭证有效时间
            final AssumeRoleResponse response = client.getAcsResponse(request);
            map.put("Expiration", response.getCredentials().getExpiration());
            map.put("AccessKeyId", response.getCredentials().getAccessKeyId());
            map.put("AccessKeySecret", response.getCredentials().getAccessKeySecret());
            map.put("SecurityToken", response.getCredentials().getSecurityToken());
            map.put("RequestId", response.getRequestId());
            map.put("DurationSeconds",DurationSeconds);
        } catch (ClientException e) {
            System.out.println("Failed:"+e.getMessage());
            System.out.println("Error code: " + e.getErrCode());
            System.out.println("Error message: " + e.getErrMsg());
            System.out.println("RequestId: " + e.getRequestId());
        }
        return map;
    }
}
